//
//  FoodTableViewController.m
//  SimpleHappy
//
//  Created by lanou on 15/11/24.
//  Copyright (c) 2015年 RockyFung. All rights reserved.
//
#import "FoodTableViewController.h"
#import "TableViewCell.h"
#import "Define.h"
#import "DetailController.h"
#import "CityModel.h"
#import "MJRefresh.h"
#import "PictureModel.h"
#import "reserveHeader.h"
#import "SHDetailModel.h"

@interface FoodTableViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,retain)NSMutableArray *reserveArray;
@property(nonatomic,retain)CityModel *cityModel;
@property(nonatomic,retain)NSMutableArray *pictureArray;
@property(nonatomic,retain)NSString *Kurl;
@property(nonatomic,retain)NSString *picKurl;
@property(nonatomic,retain)NSMutableArray *array;
@property (nonatomic,assign)NSInteger oldId;
@end
static NSInteger page = 1;
@implementation FoodTableViewController
- (NSMutableArray *)reserveArray
{
    if (!_reserveArray)
    {
        self.reserveArray = [NSMutableArray array];
    }
    return _reserveArray;
}
- (void)viewWillAppear:(BOOL)animated
{
    NSInteger newId = [[NSUserDefaults standardUserDefaults]integerForKey:@"id"];
    if (self.cityModel.baseCityId != newId)
    {
        self.reserveArray = [[NSMutableArray alloc]init];
        [self getInformationForCell];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self getInformationForHeader];
    self.array = [NSMutableArray array];
    self.tableView.rowHeight = KScreenWidth*387/750;
    [self.tableView registerClass:[TableViewCell class] forCellReuseIdentifier:@"cell"];
    //注册表头
    [self.tableView registerClass:[reserveHeader class] forHeaderFooterViewReuseIdentifier:@"head"];
    // 下拉刷新
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(headerAction)];
    // 上拉加载
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(footerAction)];
}
#pragma mark-----------请求数据--------------------------
-(void)getInformationForCell
{
    //获取citymodel
    self.cityModel = [[CityModel alloc]init];
    self.cityModel.baseCityId = [[NSUserDefaults standardUserDefaults]integerForKey:@"id"];
    NSLog(@"%ld",self.cityModel.baseCityId);
    //拼接网址
    self.Kurl=[NSString stringWithFormat:@"http://api.yhouse.com/m/meal/list?app_type=2&cityId=%ld&page=%ld",self.cityModel.baseCityId,page];
    NSURL *url = [NSURL URLWithString:_Kurl];
    //请求数据
    [[[NSURLSession sharedSession]dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (error) {
            NSLog(@"网络请求错误");
            return ;
        }
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:0];
        NSDictionary *dataDic = dic[@"data"];
      
        for (NSDictionary *docDic in dataDic[@"doc"])
        {
            ReserveModel *model = [[ReserveModel alloc]init];
            [model setValuesForKeysWithDictionary:docDic];
            [self.reserveArray addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    }]resume];

}
//---------------------------请求表头的数据-------------------------

-(void)getInformationForHeader
{
    //请求图片的信息
    //拼接网址
    self.picKurl = [NSString stringWithFormat:@"http://api.yhouse.com/m/promotion/list/2?app_type=2&cityId=1"]; //,self.cityModel.baseCityId
    NSURL *picUrl = [NSURL URLWithString:self.picKurl];
    //请求数据
    [[[NSURLSession sharedSession]dataTaskWithURL:picUrl completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (error) {
            NSLog(@"网络请求错误");
            return ;
        }
        
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:0];
        //        self.pictureArray = [[NSMutableArray alloc]init];
        self.pictureArray = [NSMutableArray array];
        for (NSDictionary *dataDic in dic[@"data"])
        {
            PictureModel *pictureModel = [[PictureModel alloc]init];
            [pictureModel setValuesForKeysWithDictionary:dataDic];
            pictureModel.shareUrl = [NSString stringWithFormat:@"http://m.yhouse.com/topic/%ld",pictureModel.id];
            [self.pictureArray addObject:pictureModel];
        }
        dispatch_sync(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];
        });
    }]resume];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.reserveArray.count;
}

#pragma mark------------返回cell----------------------
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle=NO;
    ReserveModel *model = self.reserveArray[indexPath.row];
    cell.reserveModel = model;
    
    return cell;
}
#pragma mark---------------------点击cell--------------------
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailController *detailVc = [[DetailController alloc]init];
    detailVc.hidesBottomBarWhenPushed = YES;
    ReserveModel *model = self.reserveArray[indexPath.row];
    
    SHDetailModel *SHModel = [[SHDetailModel alloc]init];
    SHModel.picUrl = model.picUrl;
    SHModel.title = model.title;
    SHModel.openUrl = model.htmlUrl;
    detailVc.SHDetailModel = SHModel;
    
    detailVc.reserveModel = model;
    detailVc.targetUrl = model.htmlUrl;

    [self.navigationController pushViewController:detailVc animated:YES];
}
#pragma mark-----------自定义表头----------------
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (self.pictureArray.count==0)
    {
        UIView *view=[[UIView alloc]init];
        return view;
    }
    else
    {
    reserveHeader *headView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"head"];
    self.array = [NSMutableArray array];
    for (PictureModel *model in self.pictureArray)
    {

        [self.array addObject:model];
    }
    headView.modelArray = self.array;
    headView.isReserve = YES;
    return headView;
    }
}
#pragma mark---------------返回表头高度------------
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    if (self.array==nil)
    {
        return 0.1;
    }
    return   KScreenWidth / 640 * 330+5;
}
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
#pragma mark-----------上拉刷新，下拉加载更多----------
// 下拉刷新
- (void)headerAction
{
    [self getInformationForCell];
    [self.tableView.header endRefreshing];
}
// 上拉加载更多
- (void)footerAction
{
    page += 1;
    [self getInformationForCell];
    [self.tableView reloadData];
    [self.tableView.footer endRefreshing];

}


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
